//
//  UIWebView+JavaScriptAlert.m
//  KissHealth
//
//  Created by 淡蓝 on 2017/1/20.
//  Copyright © 2017年 Mark. All rights reserved.
//

#import "UIWebView+JavaScriptAlert.h"

@implementation UIWebView (JavaScriptAlert)

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [customAlert show];
}

static BOOL diagStat = NO;
static NSInteger bIdx = -1;

- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:nil
                                                          message:message
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定", nil, nil];
    
    [confirmDiag show];
    bIdx = -1;
    
    while (bIdx==-1) {
        //[NSThread sleepForTimeInterval:0.2];
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
    }
    if (bIdx == 0){//取消;
        diagStat = NO;
    }
    else if (bIdx == 1) {//确定;
        diagStat = YES;
    }
    return diagStat;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    bIdx = buttonIndex;
    
    if (buttonIndex == 0)
    {
        diagStat = NO;
    }
    else if (buttonIndex == 1)
    {
        diagStat = YES;
    }

}


- (NSString *)webView:(UIWebView *)sender runJavaScriptTextInputPanelWithPrompt:(NSString *)str defaultText:(NSString *)mes initiatedByFrame:(id)frame
{
    NSString *subTitle = [NSString stringWithFormat:@"%@\n\n",str];
    UIAlertView *promptDiag = [[UIAlertView alloc] initWithTitle:nil message:subTitle delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    
    [promptDiag setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *nameField = [promptDiag textFieldAtIndex:0];
    [promptDiag show];
    
    bIdx = -1;
    while (bIdx==-1){
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
    }
    
    if (bIdx == 0){//取消;
        diagStat = NO;
    }
    else if (bIdx == 1) {//确定;
        return nameField.text;
    }
    return mes;
    
}

@end
